import React, {useState} from 'react';
import styled from 'styled-components';
import Layout from 'components/Layout';
import {NotesSection} from 'view/Money/NotesSection';
import {NumberPadSection} from 'view/Money/NumberPadSection';
import {TagsSection} from './Money/TagsSection';
import {useRecords} from 'hooks/useRecords';
import {getToday} from '../lib/dayUtils';

const MyLayout = styled(Layout)`
  display: flex;
  flex-direction: column;
`;

const today = getToday();

function Money() {
  const defaultSelected = {
    tagId: 1,
    notes: '',
    amount: 0,
    createdAt: window.localStorage.getItem('notesDate') || today
  };
  const [selected, setSelected] = useState(defaultSelected);
  const {addRecord} = useRecords();

  const onChange = (obj: Partial<typeof selected>) => {
    setSelected({
      ...selected, ...obj
    });
    if (obj.createdAt) {
      window.localStorage.setItem('notesDate', obj.createdAt);
    }
  };

  const submit = () => {
    if (addRecord(selected)) {
      alert('保存成功');
      setSelected(defaultSelected);
    }
  };

  return (
    <MyLayout>
      <TagsSection value={selected.tagId}
                   onChange={(tagId) => onChange({tagId})}/>
      <NotesSection value={selected.notes}
                    onNoteChange={(notes) => onChange({notes})}
                    createdAt={selected.createdAt}
                    today={today}
                    onDateChange={(createdAt) => onChange({createdAt})}/>
      <NumberPadSection value={selected.amount}
                        onOutputChange={(amount) => onChange({amount})}
                        onOk={submit}
      />
    </MyLayout>
  );
}

export default Money;